import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../core/utils/show_toast.dart';
import '../../../data/controllers/attendances_controller.dart';
import '../../../data/models/auth/user.dart';
import '../models/attendance.dart';

part 'user_attendances_list_state.dart';

class UserAttendancesListCubit extends Cubit<UserAttendancesListState> {
  UserAttendancesListCubit() : super(UserAttendancesListInitial());

  static UserAttendancesListCubit get(context) => BlocProvider.of(context);

  List<Attendance> attendances = [];
  late User user;

  void init({ required User user}) {
    this.user = user;

    getAllAttendances();
  }

  Future<void> getAllAttendances() async {
    emit(UserAttendancesListLoading());
    await AttendancesController.getUserAttendances( user:user).catchError((e) {
      emit(UserAttendancesListError());
      return null;
    }).then((value) {
      if (value != null && value.state) {
        attendances = List<Attendance>.generate(value.data.length, (index) =>
            Attendance.fromJson(value.data[index]));
        emit(UserAttendancesListDone());
      } else if (value != null) {
        showMessage(value.message);
        emit(UserAttendancesListError());
      } else {
        if (kDebugMode) {
          print('value is null');
        }
        emit(UserAttendancesListError());
      }
    });
  }

}
